package com.jinwei.qunguanjia.system.service;

import com.jinwei.qunguanjia.system.dto.SysLoginLogDTO;
import com.jinwei.qunguanjia.system.dto.SysLoginUser;
import com.jinwei.qunguanjia.system.dto.SysUserDTO;
import com.jinwei.qunguanjia.system.exception.UserServiceException;
import com.jinwei.qunguanjia.common.constant.CacheConstants;
import com.jinwei.qunguanjia.common.constant.Constants;
import com.jinwei.qunguanjia.common.core.redis.RedisCache;
import com.jinwei.qunguanjia.common.exception.GlobalExceptionHelper;
import com.jinwei.qunguanjia.common.exception.ServiceException;
import com.jinwei.qunguanjia.common.utils.DateUtils;
import com.jinwei.qunguanjia.common.utils.ServletUtils;
import com.jinwei.qunguanjia.common.utils.StringUtils;
import com.jinwei.qunguanjia.common.utils.TenantContextUtils;
import com.jinwei.qunguanjia.common.utils.ip.IpUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 登录校验方法
 * 
 * @author ruoyi
 */
@Component
public class SysLoginServiceImpl implements SysLoginService {

    @Resource
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private RedisCache redisCache;
    
    @Resource
    private SysUserService sysUserService;

    @Resource
    private SysConfigService sysConfigService;

    @Resource
    private SysLoginLogService sysLoginLogService;

    /**
     * 登录验证
     * 
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    @Override
    public String login(String username, String password, String code, String uuid) throws IllegalAccessException {
        boolean captchaEnabled = sysConfigService.selectCaptchaEnabled();
        // 验证码开关
        if (captchaEnabled) {
            validateCaptcha(username, code, uuid);
        }
        // 用户验证
        Authentication authentication;
        SysLoginLogDTO sysLoginLogDTO = new SysLoginLogDTO();
        sysLoginLogDTO.setUserName(username);
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                sysLoginLogDTO.setLoginStatus(Constants.LOGIN_FAIL);
                sysLoginLogDTO.setMsg(UserServiceException.USER_PASSWORD_NOT_MATCH.getMsg());
                sysLoginLogService.save(sysLoginLogDTO, ServletUtils.getRequest());
                throw GlobalExceptionHelper.localServiceException(UserServiceException.USER_PASSWORD_NOT_MATCH);
            } else if (e instanceof InternalAuthenticationServiceException) {
                sysLoginLogDTO.setLoginStatus(Constants.LOGIN_FAIL);
                sysLoginLogDTO.setMsg(e.getMessage());
                sysLoginLogService.save(sysLoginLogDTO, ServletUtils.getRequest());
                throw GlobalExceptionHelper.localServiceException((ServiceException) e.getCause());
            }else {
                sysLoginLogDTO.setLoginStatus(Constants.LOGIN_FAIL);
                sysLoginLogDTO.setMsg(e.getMessage());
                sysLoginLogService.save(sysLoginLogDTO, ServletUtils.getRequest());
                throw GlobalExceptionHelper.localServiceException(e.getMessage());
            }
        }
        sysLoginLogDTO.setLoginStatus(Constants.LOGIN_SUCCESS);
        sysLoginLogDTO.setMsg("登录成功");

        sysLoginLogService.save(sysLoginLogDTO, ServletUtils.getRequest());
        SysLoginUser loginUser = (SysLoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 校验验证码
     * 
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     */
    private void validateCaptcha(String username, String code, String uuid)
    {
        SysLoginLogDTO sysLoginLogDTO = new SysLoginLogDTO();
        sysLoginLogDTO.setUserName(username);
        String verifyKey = String.format(CacheConstants.CAPTCHA_CODE_KEY) + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null) {
            sysLoginLogDTO.setLoginStatus(Constants.LOGIN_FAIL);
            sysLoginLogDTO.setMsg(UserServiceException.USER_CAPTCHA_EXPIRE.getMsg());
            sysLoginLogService.save(sysLoginLogDTO, ServletUtils.getRequest());
            throw GlobalExceptionHelper.localServiceException(UserServiceException.USER_CAPTCHA_EXPIRE);
        }
        if (!code.equalsIgnoreCase(captcha)) {
            sysLoginLogDTO.setLoginStatus(Constants.LOGIN_FAIL);
            sysLoginLogDTO.setMsg(UserServiceException.USER_CAPTCHA_ERROR.getMsg());
            sysLoginLogService.save(sysLoginLogDTO, ServletUtils.getRequest());
            throw GlobalExceptionHelper.localServiceException(UserServiceException.USER_CAPTCHA_ERROR);
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    private void recordLoginInfo(String userId)
    {
        SysUserDTO sysUser = new SysUserDTO();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
        sysUser.setLoginDate(DateUtils.getDateTime());
        sysUserService.update(sysUser);
    }
}
